package com.lincoln.jenkins.test.game;

import com.lincoln.jenkins.test.Config;
import com.lincoln.jenkins.test.SysMsgTypeEnum;
import com.lincoln.jenkins.test.TestController;
import com.lincoln.jenkins.test.actions.SendMessage;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

public class GameContext {
    private static Map<String, Game> games = new ConcurrentHashMap<>();
    public static Queue<TestController.Task> queue = new ConcurrentLinkedQueue<>();

    /**
     * d等待加好友后发送
     */
    public static Map<String, String> waitSend = new ConcurrentHashMap<>();

    public static GameThread gameThread = null;

    public static String query(String str) {
        try {
            HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(Config.SERVERURL + "/?a=" + URLEncoder.encode(str, "UTF-8")).openConnection();
            httpURLConnection.setRequestMethod("GET");
            if (httpURLConnection.getResponseCode() != 200) {
                throw new RuntimeException("HTTP GET Request Failed with Error code : "
                        + httpURLConnection.getResponseCode());
            }
            StringBuilder builder = new StringBuilder();
            InputStream inStrm = httpURLConnection.getInputStream();
            byte[] b = new byte[1024];
            int length = -1;
            while ((length = inStrm.read(b)) != -1) {
                builder.append(new String(b, 0, length));
            }
            return builder.toString();
        } catch (Exception e) {
            return "";
        }
    }

    public static class GameThread extends Thread {
        @Override
        public void run() {
            while (true) {
                try {
                    if (queue.size() > 0) {
                        TestController.Task task = queue.poll();
                        if (task.getType() != 0) {
                            query(task.getStr());
                        }
                    }
                    if (games.size() <= 0) {
                        try {
                            sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        games.values().forEach((game) -> {
                            if (game.getGameStatus() == Game.GameStatus.WAIT && game.getWaitInNum() == -1 && game.getMaxCount() == game.getAccounts().size()) {
                                game.setGameStatus(Game.GameStatus.WAIT_IN);
                                game.setWaitInNum(0);
                                int num = new Random().nextInt(game.getAccounts().size());
                                int i = 0;
                                String wdId = null;
                                for (String key : game.getAccounts().keySet()) {
                                    if (i == num) {
                                        wdId = key;
                                        i++;
                                        break;
                                    } else {
                                        i++;
                                    }
                                }
                                game.setWdId(wdId);

                                List<Config.Account> isnotFriend = new ArrayList<>();

                                game.getAccounts().values().forEach((account) -> {
                                    //判断是否是好友
                                    String content = "你的单词是" + (account.getWxid().equals(game.getWdId()) ? game.getWrongWord() : game.getTrueWord());
                                    String res = query(new SendMessage(account.getWxid(), "你的单词是" + (account.getWxid().equals(game.getWdId()) ? game.getWrongWord() : game.getTrueWord()), "", 1).genUrl());
                                    if (res.indexOf("\"result\":[\"-2\"]") != -1) {
                                        isnotFriend.add(account);
                                        waitSend.put(account.getWxid(), waitSend.containsKey(account.getWxid()) ? (waitSend.get(account.getWxid()) + "\n" + content) : content);
                                    }
                                });


                                if (isnotFriend.size() > 0) {
                                    //提醒未加好友的加好友
                                    StringBuilder atContent = new StringBuilder();
                                    StringBuilder atList = new StringBuilder();
                                    isnotFriend.forEach((wxid) -> {
                                        atContent.append("@");
                                        atContent.append(wxid.getNickName());
                                        atContent.append(" ");
                                        atList.append("@");
                                        atList.append(wxid.getWxid());
                                        atList.append(",");
                                    });
                                    query(new SendMessage(game.getGroupId(), atContent + " 请你们尽快添加我为好友,不然不知道自己的单词!", atList.toString().substring(0, atList.toString().length() - 1), 1).genUrl());
                                }

                                i = 0;
                                num = 0;
                                wdId = null;
                                for (String key : game.getAccounts().keySet()) {
                                    if (i == num) {
                                        wdId = key;
                                        i++;
                                        break;
                                    } else {
                                        i++;
                                    }
                                }
                                queue.add(new TestController.Task(1, new SendMessage(game.getGroupId(), "@" + game.getAccounts().get(wdId).getNickName() + " 首先请第一位选手发言,记得先@我!", "@" + game.getAccounts().get(wdId).getWxid() + " ", 1).genUrl()));
                            }
                            //归票
                            if (game.getGameStatus() == Game.GameStatus.WAIT_END && game.getDone().size() == game.getAccounts().size()) {
                                Map<String, Integer> res = new HashMap<>();
                                for (String id : game.getDone().values()) {
                                    if (res.containsKey(id)) {
                                        res.put(id, res.get(id) + 1);
                                    } else {
                                        res.put(id, 1);
                                    }
                                }
                                StringBuilder atContent = new StringBuilder();
                                StringBuilder atList = new StringBuilder();
                                StringBuilder content = new StringBuilder();
                                game.getAccounts().values().forEach((aa) -> {
                                    atContent.append("@");
                                    atContent.append(aa.getNickName());
                                    atContent.append(" ");
                                    atList.append("@");
                                    atList.append(aa.getWxid());
                                    atList.append(" ");
                                });
                                res.forEach((id, num) -> {
                                    content.append(game.getAccounts().get(id).getNickName() + "---" + num + "票\n");
                                });
                                queue.add(new TestController.Task(1, new SendMessage(game.getGroupId(), atContent + " \n归票结束,结果如下:\n" + content.toString() + "卧底实际是:@" + game.getAccounts().get(game.getWdId()).getNickName() + ",正确单词:" + game.getTrueWord() + " 错误单词:" + game.getWrongWord(), game.getAccounts().get(game.getWdId()).getWxid() + " ", 1).genUrl()));
                                game.setGameStatus(Game.GameStatus.END);
                                games.remove(game);
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 讨论组是否正在游戏
     *
     * @param groupId
     * @return
     */
    public static boolean inGame(String groupId) {
        return games.containsKey(groupId);
    }

    /**
     * 新建游戏
     *
     * @param game
     */
    public static void addGame(Game game) {
        if (gameThread == null) {
            gameThread = new GameThread();
            gameThread.start();
        }
        games.put(game.getGroupId(), game);
    }

    public static void removeGame(Game game) {
        if (gameThread == null) {
            gameThread = new GameThread();
            gameThread.start();
        }
        games.remove(game.getGroupId(), game);
    }

    /**
     * 获取游戏
     *
     * @param groupId
     */
    public static Game getGame(String groupId) {
        return games.get(groupId);
    }

    public static void main(String[] args){
        int num = new Random().nextInt(2);
        System.out.println(num);
    }
}
